let moved =false

class DragController {
  startX;//开始x的位置ju
  startY;//开始y的位置
  startLeft;//开始盒子在左边的距离
  startTop;//开始盒子在上边的距离
  el; //目标元素
  runStutus = false; // 是否开始;
  directionHorizontal = true;//方向
  directionVertical = true;//方向
  elWidth;
  elParentWidth;
  constructor(el, direction = 'HV') {
    this.el = el
    if(direction === 'H') {
      this.directionVertical = false
    }else if(direction === 'V') {
      this.directionHorizontal = false
    }else if(direction !== 'HV'){
      console.log("参数不符合预期")
    }
  }
  //点击开始 移动前
  movedown(e) {
    this.isDown = true;
    this.startX = e.clientX;
    this.startY = e.clientY;
    this.startLeft = parseFloat( this.el.style.left || window.getComputedStyle(this.el).left );
    this.startTop = parseFloat( this.el.style.top || window.getComputedStyle(this.el).top );
  }
  //移动时
  moving(e) {
    if(Math.abs(e.clientX - this.startX) <=15) {
      return
    }
    moved = true //注意 这个是el触发click事件的瓶颈， 开放
    if (this.isDown) {
      if(this.directionHorizontal){
        let left = e.clientX - (this.startX - this.startLeft)
        this.elWidth = parseFloat(window.getComputedStyle(this.el).width) 
        this.elParentWidth = parseFloat(window.getComputedStyle(this.el.parentElement).width) 
        left = left <= 0 ? left : 0
        left = left >= this.elParentWidth-this.elWidth ? left : this.elParentWidth-this.elWidth
        this.el.style.left = (left <= 0 ? left : 0)+ "px";
      }
      if(this.directionVertical){
        const top = e.clientY - (this.startY - this.startTop)
        this.el.style.top = top >= 0 ? top : 0  + "px";
      } 
    }
  }
  //放开结束 移动后
  moveup(e) {
    this.isDown = false;
  }
  //方法开始
  binding() {
    const mousemove = (e)=>{
      this.moving(e)
    }
    const mouseup = (e) => {
      this.moveup(e)
      this.el.removeEventListener('mousemove', mousemove)
      this.el.removeEventListener('mouseup', mouseup)
    }
    const movedown = (e) => {
      this.movedown(e)
      this.el.addEventListener('mousemove', mousemove)
      this.el.addEventListener('mouseup', mouseup)
    }

    //触发移动时，阻止链接跳转
    const clickFunctopn = function (e) { 
      if(moved) {
        e.stopPropagation()
        moved = false //注意这里的处理
      }  
    }


    //移入开始监听点击下按事件
    this.el.addEventListener('mouseenter', ()=>{
      this.el.addEventListener('mousedown', movedown)
      this.el.addEventListener('click', clickFunctopn, true)
    })

    //移出开始移除所有事件鼠标拖动事件
    this.el.addEventListener('mouseleave', ()=>{
      this.el.removeEventListener('mousedown', movedown)
      this.el.removeEventListener('mousemove', mousemove)
      this.el.removeEventListener('mouseup', mouseup)
      this.el.removeEventListener('click', clickFunctopn, true)
    })
    
  }
}

export default DragController